package com.open4cn.simulator.protocol.xrite;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author yinxiaopeng
 * @version 1.0.0
 * @company 致景科技
 * @department 飞梭BU/研发
 * @description
 * @Email yinxiaopeng@zj.tech
 * @date 2022-05-13 00:44
 */
public class XriteDecoder extends ByteToMessageDecoder {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        byte[] array = new byte[in.readableBytes()];
        in.readBytes(array);
        // 指令必须以回车结尾
        int length = array.length;
        if (length <= 1) {
            logger.warn("[XriteDecoder]指令长度不正确");
            out.add("instruction length error");
            return;
        }

        byte[] endFlag = new byte[1];
        endFlag[0] = array[length - 1];
        if (!"\r".equals(new String(endFlag, StandardCharsets.US_ASCII))) {
            logger.warn("[XriteDecoder]指令结束符不正确");
            out.add("instruction end error");
            return;
        }

        byte[] context = new byte[length - 1];
        for (int i = 0; i < length - 1; i++) {
            context[i] = array[i];
        }
        out.add(new String(context, StandardCharsets.US_ASCII));
    }
}
